<?php

require_once(__DIR__.'/../../../../wp-load.php');

function exit_with($msg) {
    header('HTTP/1.0 401 Unauthorized');
    header('Content-Type: application/json');
    echo json_encode([
        'code' => 401,
        'error' => $msg
    ]);
    exit;
}

$mobile_num = $_POST['mobile'];

if (!preg_match('/^1([0-9]{9})/', $mobile_num)) {
    exit_with('手机号不正确');
}

$latest_code = get_option('verify:'.$mobile_num);
$current_time = time();

if ($latest_code) {
    $msg_code = $latest_code['code'];
    $latest_time = $latest_code['time'];

    if ($current_time < $latest_time + 20) {
        exit_with('发送验证码时间间隔过短。');
    }
}
else {
    $msg_code = mt_rand(1000,9999);
}

$app_key = 'b8631b965213244518fa93c1ae29b1cf';
$msg_content = '【比案网】您的验证码是'.$msg_code.'';

// 记录到数据库
$verify = get_option('verify:'.$mobile_num);
if ($verify) {
    update_option('verify:'.$mobile_num, [
        'code' => $msg_code,
        'time' => $current_time
    ]);
}
else {
    add_option('verify:'.$mobile_num, [
        'code' => $msg_code,
        'time' => $current_time
    ]);
}

$ch = curl_init();
$data = [
    'text' => $msg_content,
    'apikey' => $app_key,
    'mobile' => $mobile_num
];

curl_setopt ($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/single_send.json');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept:text/plain;charset=utf-8', 
    'Content-Type:application/x-www-form-urlencoded', 
    'charset=utf-8'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$response = curl_exec($ch);
curl_close($ch);

$return = json_decode($response, true);
header('Content-Type: application/json');
echo json_encode([
    'code' => 200,
    'data' => $return
]);
exit;